package com.xzx;

import jakarta.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/9/3 22:31
 */
public class Producer2Topic {
    public static void main(String[] args) {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        try {
            // connection是比较耗性能的动作，应该池化
            connection = activeMQConnectionFactory.createConnection();
            // 生产者这个方法不调用没事
            connection.start();

            session = connection.createSession();
            Topic topic = session.createTopic("xzx_topic");
            producer = session.createProducer(topic);
            TextMessage message = session.createTextMessage("hello world");
            producer.send(message);
            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        } finally {
            close(producer);
            close(session);
            close(connection);
        }

    }

    private static void close(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}